package org.aplikator.client.widgets;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HTML;

public class ProgressTimer extends Timer {

    private static final Logger LOG = Logger.getLogger(ProgressTimer.class.getName());

    private HTML statusLabel;
    private boolean running = false;

    public ProgressTimer(HTML statusLabel) {
        this.statusLabel = statusLabel;

        // make one call to the server to make sure we have a session
        retrieveCurrentProgressFromServer();
    }

    public void run() {
        if (!running) {
            return;
        }

        retrieveCurrentProgressFromServer();
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    protected void retrieveCurrentProgressFromServer() {
        // System.out.println("calling the server for the status");
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + "upload");
        builder.setCallback(new RequestCallback() {
            public void onResponseReceived(Request request, Response response) {
                // StringBuilder builder = new
                // StringBuilder("reponse received: ");
                // builder.append(response.getStatusCode()).append(" - ").append(response.getStatusText()).append("\n\t content: ").append(response.getText());
                // System.out.println(builder.toString());

                statusLabel.setText(response.getText());
            }

            public void onError(Request request, Throwable t) {
                LOG.log(Level.SEVERE, "Unable to retrieve the current status from the server", t);
            }
        });

        try {
            builder.send();
        } catch (RequestException e) {
            LOG.log(Level.SEVERE, "An error occurred while connecting to the file upload monitor", e);
        }
    }

}
